/**
 * 倾向性
 */
var Wechat = require('../../models/wechat/scrapyModel').Wechat;
var WechatStat = require('../../models/wechat/statModel').WechatStat;
var Keyword = require('../../models/keywordsModel').Keyword;
var Util = require('../../util/util');
var Spare = require('../../util/spareData');

function main(){
    console.log('微信 倾向性 开始');
    FindAllKeywords();
}

function FindAllKeywords(){
    Keyword.findAllKeywords(function (err, docs) {
        var list = [];
        if (err) {
            console.log(err);
        }
        for (var i in docs) {
            list.push({
                'keyword_id': docs[i]._id,
                'title': docs[i].title
            })
        }
        ListForEach(list,function(){
            console.log('===============  微信 倾向性 统计 所有完成了！！');
        })

    });
}

function ListForEach(list,callback){
    //同步
    var i,getTitle,findByTitle,sentimentStat,initExport,insertStat,next,done;
    i = 0;

    getTitle = function(){
        if(i>=list.length){
            return done();
        }
        console.log('获取题目....'+list[i].title);
        findByTitle(list[i]);
    };

    findByTitle = function(list){
        Wechat.findByKeyword(list.title,function(err,data){
            console.log('获取'+list.title+'的数据长度....'+data.length);
            sentimentStat(list,data);
        });
    };

    sentimentStat = function(list,data){
        console.log('倾向性统计...'+list.title);
        var high = Spare.wechatSpare.threshold.high,
            low = Spare.wechatSpare.threshold.low;
        var sentiment = {
            "positive": 0,
            "negative": 0,
            "neutral": 0
        };
        for (var d in data) {
            var sent = data[d].sentiment;
            //varify
            if (sent > high) {
                //positive
                sentiment.positive++;
            }
            else if (sent > 0 && sent < low) {
                sentiment.negative++;
            }
            else if (sent >= low && sent <= high) {
                sentiment.neutral++;
            }
        }
        initExport(list,sentiment);

    };

    initExport = function(list,sentiment){
        var exportData = [];
        exportData.push(sentiment);
        insertStat(list,exportData);
    };

    insertStat = function(list,exportData){
        //console.log(exportData);
        WechatStat.saveSentiment(list.keyword_id,list.title,exportData);
        next(list);
    };

    next = function(list){
        console.log('已经完成啦....'+list.title);
        ++i;
        getTitle();
    };

    done = function(){
        callback();
    };

    return getTitle();
}

exports.main = main;

